const VERSION = "1.1.8"
const DESC = "版本更新"
const fs = require('fs');
const path = require('path');
// 指定文件夹路径
const cluster = require('cluster');
const folderPath = 'keys';
const ci = require('miniprogram-ci');
if (cluster.isMaster) {
	// 获取文件夹中的所有文件
	const files = fs.readdirSync(folderPath)
	// 过滤出所有扩展名为.key的文件
	const keyFiles = files.filter(file => path.extname(file).toLowerCase() === '.key');
	for (let index in keyFiles) {
		const file = keyFiles[index];
		const path = "keys/" + file
		const temp = file.split(".")
		const appid = temp[1]
		const projectname = temp[0]
		const worker = cluster.fork() // 启动子进程
		// 发送任务数据给执行进程，并监听子进程回传的消息
		worker.send({
			appid,
			projectname,
		});
		worker.on('message', message => {
			console.log(message)
			worker.kill();
		});
	}
	cluster.on('exit', worker => {
		console.log('worker ' + worker.process.pid + ' killed!');
		if (Object.keys(cluster.workers).length === 0) {
			console.log('calculate main process end');
		}
	});
} else {
	process.on('message', message => {
		const {
			appid,
			projectname
		} = message
		upload(appid, projectname).then(() => {
			process.send("over");
		})
	})
}

function copyFolderSync(source, target) {
	// 创建目标文件夹
	if (!fs.existsSync(target)) {
		fs.mkdirSync(target, {
			recursive: true
		});
	}

	// 读取源文件夹的内容
	const entries = fs.readdirSync(source, {
		withFileTypes: true
	});

	// 遍历并复制每个文件/子文件夹
	for (const entry of entries) {
		const srcPath = path.join(source, entry.name);
		const destPath = path.join(target, entry.name);

		if (entry.isDirectory()) {
			// 递归复制子文件夹
			copyFolderSync(srcPath, destPath);
		} else {
			// 复制文件
			fs.copyFileSync(srcPath, destPath);
		}
	}
}
async function upload(appid, projectname) {
	console.log(projectname + ":开始推送")
	try {
		if (fs.existsSync("unpackage/dist/dev/" + appid)) {
			fs.rmdirSync("unpackage/dist/dev/" + appid, {
				recursive: true
			})
		}
		copyFolderSync("unpackage/dist/dev/mp-weixin", "unpackage/dist/dev/" + appid)
		const config = JSON.parse(fs.readFileSync('unpackage/dist/dev/' + appid + '/project.config.json')
			.toString())
		config.projectname = projectname
		config.appid = appid
		fs.writeFileSync('unpackage/dist/dev/' + appid + '/project.config.json', JSON.stringify(config))
		const project = new ci.Project({
			appid: appid,
			type: 'miniProgram',
			projectPath: "unpackage/dist/dev/" + appid,
			privateKeyPath: "keys/" + projectname + "." + appid + ".key",
			ignores: ['node_modules/**/*'],
		})
		const uploadResult = await ci.upload({
			project,
			version: VERSION,
			desc: DESC,
			setting: {
				es6: true,
			}
		})
	} catch (e) {
		console.log(projectname + ":推送失败")
		console.log(e)
	}
	fs.rmdirSync("unpackage/dist/dev/" + appid, {
		recursive: true
	})
	console.log(projectname + ":推送成功")
}